#include "mainwindow.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cmath>

MainWindow::MainWindow()
    : m_main_box(Gtk::ORIENTATION_VERTICAL),
      m_button_box(Gtk::ORIENTATION_HORIZONTAL),
      m_process_box(Gtk::ORIENTATION_VERTICAL),
      m_filter_box(Gtk::ORIENTATION_HORIZONTAL),
      m_performance_box(Gtk::ORIENTATION_VERTICAL),
      m_perf_summary_box(Gtk::ORIENTATION_VERTICAL),
      m_perf_detail_box(Gtk::ORIENTATION_VERTICAL),
      m_cpu_button(),
      m_memory_button(),
      m_disk_button(),
      m_cpu_label(),
      m_memory_label(),
      m_disk_label(),
      m_system_info_box(Gtk::ORIENTATION_VERTICAL),
      m_system_info_title(),
      m_system_info_grid(),
      m_os_label_title("操作系统:"),
      m_os_label_value(),
      m_kernel_label_title("内核版本:"),
      m_kernel_label_value(),
      m_hostname_label_title("主机名:"),
      m_hostname_label_value(),
      m_uptime_label_title("运行时间:"),
      m_uptime_label_value(),
      m_load_label_title("负载均衡:"),
      m_load_label_value(),
      m_processes_label_title("进程数:"),
      m_processes_label_value(),
      m_cpu_model_label_title("CPU型号:"),
      m_cpu_model_label_value(),
      m_cpu_cores_label_title("CPU核心数:"),
      m_cpu_cores_label_value(),
      m_network_label_title("网络使用:"),
      m_network_label_value(),
      m_cpu_detail_box(Gtk::ORIENTATION_VERTICAL),
      m_cpu_graph_box(Gtk::ORIENTATION_VERTICAL),
      m_cpu_info_box(Gtk::ORIENTATION_HORIZONTAL),
      m_memory_detail_box(Gtk::ORIENTATION_VERTICAL),
      m_memory_graph_box(Gtk::ORIENTATION_VERTICAL),
      m_memory_info_box(Gtk::ORIENTATION_HORIZONTAL),
      m_disk_detail_box(Gtk::ORIENTATION_VERTICAL),
      m_disk_graph_box(Gtk::ORIENTATION_VERTICAL),
      m_disk_info_box(Gtk::ORIENTATION_HORIZONTAL),
      m_cpu_frame(),
      m_memory_frame(),
      m_disk_frame(),
      m_app_history_box(Gtk::ORIENTATION_VERTICAL),
      m_startup_box(Gtk::ORIENTATION_VERTICAL),
      m_toolbox_box(Gtk::ORIENTATION_VERTICAL),
      m_ai_master_box(Gtk::ORIENTATION_VERTICAL),
      m_all_processes_radio("所有进程"),
      m_user_processes_radio("用户进程"),
      m_system_processes_radio("系统进程"),
      m_services_radio("后台服务"),
      m_refresh_button("刷新"),
      m_end_task_button("结束任务"),
      m_new_task_button("新任务"),
      m_process_timer(),
      m_system_timer(),
      m_last_selected_pid(-1),
      m_last_selected_filter(0) {
    
    // 设置窗口属性
    set_title("任务管理器");
    set_border_width(10);

    // 初始化过滤器单选按钮
    m_all_processes_radio.set_active(true);
    
    // 将单选按钮加入组
    m_user_processes_radio.join_group(m_all_processes_radio);
    m_system_processes_radio.join_group(m_all_processes_radio);
    m_services_radio.join_group(m_all_processes_radio);
    
    // 连接信号
    m_refresh_button.signal_clicked().connect(
        sigc::mem_fun(*this, &MainWindow::on_refresh_button_clicked));
    m_end_task_button.signal_clicked().connect(
        sigc::mem_fun(*this, &MainWindow::on_end_task_button_clicked));
    m_new_task_button.signal_clicked().connect(
        sigc::mem_fun(*this, &MainWindow::on_new_task_button_clicked));
    
    // 过滤器信号
    m_all_processes_radio.signal_toggled().connect(
        sigc::mem_fun(*this, &MainWindow::on_process_filter_changed));
    m_user_processes_radio.signal_toggled().connect(
        sigc::mem_fun(*this, &MainWindow::on_process_filter_changed));
    m_system_processes_radio.signal_toggled().connect(
        sigc::mem_fun(*this, &MainWindow::on_process_filter_changed));
    m_services_radio.signal_toggled().connect(
        sigc::mem_fun(*this, &MainWindow::on_process_filter_changed));
    
    // 设置笔记本页面切换信号 - 使用lambda表达式来忽略参数
    m_notebook.signal_switch_page().connect([this](Gtk::Widget* page, guint page_num) {
        this->on_tab_changed();
    });

    // 构建进程页面
    m_filter_box.pack_start(m_all_processes_radio, false, false, 5);
    m_filter_box.pack_start(m_user_processes_radio, false, false, 5);
    m_filter_box.pack_start(m_system_processes_radio, false, false, 5);
    m_filter_box.pack_start(m_services_radio, false, false, 5);
    m_filter_box.set_spacing(10);
    
    m_process_box.pack_start(m_filter_box, false, false, 5);
    m_process_box.pack_start(m_process_table, true, true, 5);
    
    // 构建性能页面 - 概览页面
    // 创建性能概览按钮
    m_cpu_button.set_label("CPU\n0.0%");
    m_memory_button.set_label("内存\n0.0%");
    m_disk_button.set_label("磁盘\n0.0 MB/s");
    m_network_button.set_label("网络\n0.0 MB/s");  // 添加网络按钮
    
    // 设置按钮样式
    m_cpu_button.set_size_request(150, 100);
    m_memory_button.set_size_request(150, 100);
    m_disk_button.set_size_request(150, 100);
    m_network_button.set_size_request(150, 100);  // 设置网络按钮样式
    
    // 设置按钮文本左对齐
    m_cpu_button.set_halign(Gtk::ALIGN_START);
    m_memory_button.set_halign(Gtk::ALIGN_START);
    m_disk_button.set_halign(Gtk::ALIGN_START);
    m_network_button.set_halign(Gtk::ALIGN_START);
    
    // 连接按钮点击信号
    m_cpu_button.signal_clicked().connect([this]() {
        // 显示CPU详情页面
        m_cpu_detail_box.show();
        m_memory_detail_box.hide();
        m_disk_detail_box.hide();
        m_perf_summary_box.hide();
    });
    
    m_memory_button.signal_clicked().connect([this]() {
        // 显示内存详情页面
        m_cpu_detail_box.hide();
        m_memory_detail_box.show();
        m_disk_detail_box.hide();
        m_perf_summary_box.hide();
    });
    
    m_disk_button.signal_clicked().connect([this]() {
        // 显示磁盘详情页面
        m_cpu_detail_box.hide();
        m_memory_detail_box.hide();
        m_disk_detail_box.show();
        m_perf_summary_box.hide();
    });
    
    m_network_button.signal_clicked().connect([this]() {
        // 显示网络详情页面（暂时显示CPU详情页面）
        m_cpu_detail_box.show();
        m_memory_detail_box.hide();
        m_disk_detail_box.hide();
        m_perf_summary_box.hide();
    });
    
    // 创建概览布局
    Gtk::Box* perf_buttons_box = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 10));
    perf_buttons_box->set_halign(Gtk::ALIGN_CENTER);
    perf_buttons_box->set_valign(Gtk::ALIGN_CENTER);
    perf_buttons_box->pack_start(m_cpu_button, Gtk::PACK_SHRINK);
    perf_buttons_box->pack_start(m_memory_button, Gtk::PACK_SHRINK);
    perf_buttons_box->pack_start(m_disk_button, Gtk::PACK_SHRINK);
    perf_buttons_box->pack_start(m_network_button, Gtk::PACK_SHRINK);  // 添加网络按钮到布局
    
    // 创建系统信息显示区域
    m_system_info_title.set_halign(Gtk::ALIGN_START);
    m_system_info_title.set_markup("<span size='large' weight='bold'>系统信息</span>");
    
    // 设置系统信息标签左对齐
    m_os_label_title.set_halign(Gtk::ALIGN_START);
    m_os_label_value.set_halign(Gtk::ALIGN_START);
    m_kernel_label_title.set_halign(Gtk::ALIGN_START);
    m_kernel_label_value.set_halign(Gtk::ALIGN_START);
    m_hostname_label_title.set_halign(Gtk::ALIGN_START);
    m_hostname_label_value.set_halign(Gtk::ALIGN_START);
    m_distro_label_title.set_halign(Gtk::ALIGN_START);
    m_distro_label_value.set_halign(Gtk::ALIGN_START);
    m_uptime_label_title.set_halign(Gtk::ALIGN_START);
    m_uptime_label_value.set_halign(Gtk::ALIGN_START);
    m_load_label_title.set_halign(Gtk::ALIGN_START);
    m_load_label_value.set_halign(Gtk::ALIGN_START);
    m_processes_label_title.set_halign(Gtk::ALIGN_START);
    m_processes_label_value.set_halign(Gtk::ALIGN_START);
    m_cpu_model_label_title.set_halign(Gtk::ALIGN_START);
    m_cpu_model_label_value.set_halign(Gtk::ALIGN_START);
    m_cpu_cores_label_title.set_halign(Gtk::ALIGN_START);
    m_cpu_cores_label_value.set_halign(Gtk::ALIGN_START);
    m_network_label_title.set_halign(Gtk::ALIGN_START);
    m_network_label_value.set_halign(Gtk::ALIGN_START);
    
    // 设置网格布局
    m_system_info_grid.set_column_spacing(10);
    m_system_info_grid.set_row_spacing(5);
    m_system_info_grid.set_halign(Gtk::ALIGN_START);
    m_system_info_grid.set_valign(Gtk::ALIGN_START);
    
    // 添加系统信息到网格
    m_system_info_grid.attach(m_os_label_title, 0, 0, 1, 1);
    m_system_info_grid.attach(m_os_label_value, 1, 0, 1, 1);
    
    m_system_info_grid.attach(m_kernel_label_title, 0, 1, 1, 1);
    m_system_info_grid.attach(m_kernel_label_value, 1, 1, 1, 1);
    
    m_system_info_grid.attach(m_hostname_label_title, 0, 2, 1, 1);
    m_system_info_grid.attach(m_hostname_label_value, 1, 2, 1, 1);
    
    // 修复显示重影问题 - 确保每行只显示一个信息项
    m_system_info_grid.attach(m_distro_label_title, 0, 3, 1, 1);
    m_system_info_grid.attach(m_distro_label_value, 1, 3, 1, 1);
    
    m_system_info_grid.attach(m_uptime_label_title, 0, 4, 1, 1);
    m_system_info_grid.attach(m_uptime_label_value, 1, 4, 1, 1);
    
    m_system_info_grid.attach(m_load_label_title, 0, 5, 1, 1);
    m_system_info_grid.attach(m_load_label_value, 1, 5, 1, 1);
    
    m_system_info_grid.attach(m_processes_label_title, 0, 6, 1, 1);
    m_system_info_grid.attach(m_processes_label_value, 1, 6, 1, 1);
    
    m_system_info_grid.attach(m_cpu_model_label_title, 0, 7, 1, 1);
    m_system_info_grid.attach(m_cpu_model_label_value, 1, 7, 1, 1);
    
    m_system_info_grid.attach(m_cpu_cores_label_title, 0, 8, 1, 1);
    m_system_info_grid.attach(m_cpu_cores_label_value, 1, 8, 1, 1);
    
    m_system_info_grid.attach(m_network_label_title, 0, 9, 1, 1);
    m_system_info_grid.attach(m_network_label_value, 1, 9, 1, 1);
    
    m_system_info_box.pack_start(m_system_info_grid, Gtk::PACK_EXPAND_WIDGET);
    m_system_info_box.set_margin_start(20);
    m_system_info_box.set_margin_end(20);
    m_system_info_box.set_margin_top(10);
    m_system_info_box.set_margin_bottom(10);
    
    // 将性能按钮和系统信息添加到概览框
    m_perf_summary_box.pack_start(*perf_buttons_box, Gtk::PACK_SHRINK);
    m_perf_summary_box.pack_start(m_system_info_box, Gtk::PACK_EXPAND_WIDGET);
    m_perf_summary_box.set_halign(Gtk::ALIGN_CENTER);
    m_perf_summary_box.set_valign(Gtk::ALIGN_CENTER);
    
    // 创建CPU详细页面
    m_cpu_frame.add(m_cpu_drawing_area);
    m_cpu_frame.set_label("CPU使用率");
    m_cpu_graph_box.pack_start(m_cpu_frame, Gtk::PACK_EXPAND_WIDGET);
    
    m_cpu_info_label.set_text("CPU详细信息");
    m_cpu_info_label.set_halign(Gtk::ALIGN_START);
    m_cpu_info_box.pack_start(m_cpu_info_label, Gtk::PACK_SHRINK);
    
    m_cpu_back_button.set_label("返回");
    m_cpu_back_button.signal_clicked().connect([this]() {
        m_notebook.set_current_page(1); // 返回性能标签页
    });
    m_cpu_info_box.pack_end(m_cpu_back_button, Gtk::PACK_SHRINK);
    
    m_cpu_detail_box.pack_start(m_cpu_graph_box, Gtk::PACK_EXPAND_WIDGET);
    m_cpu_detail_box.pack_start(m_cpu_info_box, Gtk::PACK_SHRINK);
    
    // 创建内存详细页面
    m_memory_frame.add(m_memory_drawing_area);
    m_memory_frame.set_label("内存使用");
    m_memory_graph_box.pack_start(m_memory_frame, Gtk::PACK_EXPAND_WIDGET);
    
    m_memory_info_label.set_text("内存详细信息");
    m_memory_info_label.set_halign(Gtk::ALIGN_START);
    m_memory_info_box.pack_start(m_memory_info_label, Gtk::PACK_SHRINK);
    
    m_memory_back_button.set_label("返回");
    m_memory_back_button.signal_clicked().connect([this]() {
        m_notebook.set_current_page(1); // 返回性能标签页
    });
    m_memory_info_box.pack_end(m_memory_back_button, Gtk::PACK_SHRINK);
    
    m_memory_detail_box.pack_start(m_memory_graph_box, Gtk::PACK_EXPAND_WIDGET);
    m_memory_detail_box.pack_start(m_memory_info_box, Gtk::PACK_SHRINK);
    
    // 创建磁盘详细页面
    m_disk_frame.add(m_disk_drawing_area);
    m_disk_frame.set_label("磁盘使用");
    m_disk_graph_box.pack_start(m_disk_frame, Gtk::PACK_EXPAND_WIDGET);
    
    m_disk_info_label.set_text("磁盘使用量: 20.0 GB / 100.0 GB\n读写速度: 0.0 MB/s");
    m_disk_info_label.set_halign(Gtk::ALIGN_START);
    m_disk_info_box.pack_start(m_disk_info_label, Gtk::PACK_SHRINK);
    
    m_disk_back_button.set_label("返回");
    m_disk_back_button.signal_clicked().connect([this]() {
        m_notebook.set_current_page(1); // 返回性能标签页
    });
    m_disk_info_box.pack_end(m_disk_back_button, Gtk::PACK_SHRINK);
    
    m_disk_detail_box.pack_start(m_disk_graph_box, Gtk::PACK_EXPAND_WIDGET);
    m_disk_detail_box.pack_start(m_disk_info_box, Gtk::PACK_SHRINK);
    
    // 初始化时隐藏详情页面
    m_cpu_detail_box.hide();
    m_memory_detail_box.hide();
    m_disk_detail_box.hide();
    
    // 连接绘图信号
    m_cpu_drawing_area.signal_draw().connect(
        sigc::mem_fun(*this, &MainWindow::on_cpu_draw));
    m_memory_drawing_area.signal_draw().connect(
        sigc::mem_fun(*this, &MainWindow::on_memory_draw));
    m_disk_drawing_area.signal_draw().connect(
        sigc::mem_fun(*this, &MainWindow::on_disk_draw));

    // 添加页面到笔记本 - 移除单独的性能详情页面
    m_performance_box.pack_start(m_perf_summary_box, Gtk::PACK_EXPAND_WIDGET);
    m_notebook.append_page(m_process_box, "进程");
    m_notebook.append_page(m_performance_box, "性能");
    m_notebook.append_page(m_app_history_box, "应用历史记录");
    m_notebook.append_page(m_startup_box, "启动");
    m_notebook.append_page(m_toolbox_box, "工具箱");
    m_notebook.append_page(m_ai_master_box, "AI管家");
    
    // 构建其他页面
    // 应用历史记录标签页
    Gtk::ScrolledWindow app_history_scrolled_window;
    Gtk::TreeView app_history_tree_view;
    
    // 创建应用历史记录的数据模型
    m_app_history_liststore = Gtk::ListStore::create(m_app_history_columns);
    app_history_tree_view.set_model(m_app_history_liststore);
    
    // 添加列
    app_history_tree_view.append_column("应用名称", m_app_history_columns.m_col_app_name);
    app_history_tree_view.append_column("首次运行", m_app_history_columns.m_col_first_run);
    app_history_tree_view.append_column("最后运行", m_app_history_columns.m_col_last_run);
    app_history_tree_view.append_column("运行次数", m_app_history_columns.m_col_run_count);
    
    app_history_scrolled_window.add(app_history_tree_view);
    m_app_history_box.pack_start(app_history_scrolled_window, true, true, 0);
    
    // 启动标签页
    Gtk::ScrolledWindow startup_scrolled_window;
    Gtk::TreeView startup_tree_view;
    
    // 创建启动项的数据模型
    m_startup_liststore = Gtk::ListStore::create(m_startup_columns);
    startup_tree_view.set_model(m_startup_liststore);
    
    // 添加列
    startup_tree_view.append_column("名称", m_startup_columns.m_col_startup_name);
    startup_tree_view.append_column("命令", m_startup_columns.m_col_startup_command);
    startup_tree_view.append_column("状态", m_startup_columns.m_col_startup_status);
    
    startup_scrolled_window.add(startup_tree_view);
    m_startup_box.pack_start(startup_scrolled_window, true, true, 0);
    
    // 工具箱标签页
    Gtk::ScrolledWindow toolbox_scrolled_window;
    Gtk::TreeView toolbox_tree_view;
    
    // 创建工具箱的数据模型
    m_toolbox_liststore = Gtk::ListStore::create(m_toolbox_columns);
    toolbox_tree_view.set_model(m_toolbox_liststore);
    
    // 添加列
    toolbox_tree_view.append_column("工具名称", m_toolbox_columns.m_col_username);
    toolbox_tree_view.append_column("状态", m_toolbox_columns.m_col_uid);
    toolbox_tree_view.append_column("描述", m_toolbox_columns.m_col_gid);
    
    toolbox_scrolled_window.add(toolbox_tree_view);
    m_toolbox_box.pack_start(toolbox_scrolled_window, true, true, 0);
    
    // AI管家标签页
    Gtk::ScrolledWindow ai_master_scrolled_window;
    Gtk::TreeView ai_master_tree_view;
    
    // 创建AI管家的数据模型
    m_ai_master_liststore = Gtk::ListStore::create(m_ai_master_columns);
    ai_master_tree_view.set_model(m_ai_master_liststore);
    
    // 添加列
    ai_master_tree_view.append_column("功能名称", m_ai_master_columns.m_col_service_name);
    ai_master_tree_view.append_column("状态", m_ai_master_columns.m_col_service_status);
    ai_master_tree_view.append_column("描述", m_ai_master_columns.m_col_service_description);
    
    ai_master_scrolled_window.add(ai_master_tree_view);
    m_ai_master_box.pack_start(ai_master_scrolled_window, true, true, 0);
    
    // 构建按钮区域
    m_button_box.pack_start(m_refresh_button, false, false, 5);
    m_button_box.pack_end(m_new_task_button, false, false, 5);
    m_button_box.pack_end(m_end_task_button, false, false, 5);
    
    // 添加所有组件到主布局
    m_main_box.pack_start(m_notebook, true, true, 5);
    m_main_box.pack_start(m_button_box, false, false, 5);
    
    add(m_main_box);
    
    // 显示所有组件
    show_all_children();
    
    // 启动定时器
    m_process_timer = Glib::signal_timeout().connect(
        sigc::mem_fun(*this, &MainWindow::on_process_timer_callback), 3000);
    
    m_system_timer = Glib::signal_timeout().connect(
        sigc::mem_fun(*this, &MainWindow::on_system_timer_callback), 2000);
    
    // 初始加载进程
    on_refresh_button_clicked();
}

MainWindow::~MainWindow() {
    // 断开定时器
    if (m_process_timer.connected()) {
        m_process_timer.disconnect();
    }
    
    if (m_system_timer.connected()) {
        m_system_timer.disconnect();
    }
    
    // 不再手动隐藏ProcessTable，让GTK自动处理子控件的清理
    // m_process_table.hide();
}

void MainWindow::on_refresh_button_clicked() {
    // 获取当前过滤器
    std::string filter = "all";
    if (m_user_processes_radio.get_active()) {
        filter = "user";
    } else if (m_system_processes_radio.get_active()) {
        filter = "system";
    } else if (m_services_radio.get_active()) {
        filter = "services";
    }
    
    // 刷新进程数据
    std::vector<ProcessInfo> processes;
    if (filter == "user") {
        processes = m_process_manager.get_user_processes();
    } else if (filter == "system") {
        processes = m_process_manager.get_system_processes();
    } else if (filter == "services") {
        processes = m_process_manager.get_service_processes();
    } else {
        processes = m_process_manager.get_all_processes();
    }
    
    m_process_table.update_data(processes);
}

void MainWindow::on_end_task_button_clicked() {
    // 获取选中的进程PID
    int selected_pid = m_process_table.get_selected_pid();
    if (selected_pid > 0) {
        // 终止选中的进程
        m_process_manager.kill_process(selected_pid);
        
        // 刷新进程列表
        on_refresh_button_clicked();
    }
}

void MainWindow::on_new_task_button_clicked() {
    // 创建一个对话框用于输入命令
    Gtk::Dialog dialog("新建任务", *this, true);
    dialog.add_button("取消", Gtk::RESPONSE_CANCEL);
    dialog.add_button("确定", Gtk::RESPONSE_OK);
    dialog.set_default_response(Gtk::RESPONSE_OK);
    
    Gtk::Box* content_area = dialog.get_content_area();
    
    Gtk::Box hbox(Gtk::ORIENTATION_HORIZONTAL, 5);
    hbox.set_border_width(10);
    
    Gtk::Label label("命令:");
    hbox.pack_start(label, false, false);
    
    Gtk::Entry entry;
    entry.set_text("/bin/");
    hbox.pack_start(entry, true, true);
    
    content_area->pack_start(hbox, false, false);
    content_area->show_all_children();
    
    dialog.signal_response().connect([&](int response_id) {
        if (response_id == Gtk::RESPONSE_OK) {
            Glib::ustring command = entry.get_text();
            if (!command.empty()) {
                try {
                    // 分割命令和参数
                    std::vector<std::string> args;
                    std::istringstream iss(command);
                    std::string arg;
                    while (iss >> arg) {
                        args.push_back(arg);
                    }
                    
                    if (!args.empty()) {
                        // 启动新进程
                        Glib::spawn_async("", args, Glib::SpawnFlags::SPAWN_SEARCH_PATH);
                    }
                } catch (const Glib::Error& ex) {
                    // 显示错误对话框
                    Gtk::MessageDialog error_dialog(dialog, "无法启动进程: " + ex.what(), false, 
                                                    Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
                    error_dialog.run();
                }
            }
        }
        dialog.hide();
    });
    
    dialog.show();
}

void MainWindow::on_process_filter_changed() {
    // 记忆当前选中的过滤器
    if (m_all_processes_radio.get_active()) {
        m_last_selected_filter = 0;
    } else if (m_user_processes_radio.get_active()) {
        m_last_selected_filter = 1;
    } else if (m_system_processes_radio.get_active()) {
        m_last_selected_filter = 2;
    } else if (m_services_radio.get_active()) {
        m_last_selected_filter = 3;
    }
    
    // 过滤器改变时刷新进程列表
    on_refresh_button_clicked();
}

void MainWindow::on_tab_changed() {
    // 当切换到性能标签页时更新系统信息
    if (m_notebook.get_current_page() == 1) { // 性能标签页
        on_system_info_update();
    }
}

bool MainWindow::on_process_timer_callback() {
    // 获取当前选中的进程PID
    m_last_selected_pid = m_process_table.get_selected_pid();
    
    // 保存当前的选择状态
    Glib::RefPtr<Gtk::TreeSelection> selection = m_process_table.get_selection();
    std::vector<Gtk::TreeModel::Path> selected_paths = selection->get_selected_rows();
    
    // 更新进程数据
    std::vector<ProcessInfo> processes;
    
    // 根据记忆的过滤器设置获取相应的进程列表
    switch (m_last_selected_filter) {
        case 1: // 用户进程
            processes = m_process_manager.get_user_processes();
            break;
        case 2: // 系统进程
            processes = m_process_manager.get_system_processes();
            break;
        case 3: // 后台服务
            processes = m_process_manager.get_service_processes();
            break;
        default: // 所有进程
            processes = m_process_manager.get_processes();
            break;
    }
    
    m_process_table.update_data(processes);
    
    // 如果之前有选中的进程，尝试重新选中它
    if (m_last_selected_pid > 0) {
        m_process_table.set_selected_pid(m_last_selected_pid);
    }
    // 如果有选中的行路径（处理排序情况），尝试恢复选择
    else if (!selected_paths.empty()) {
        // 获取新的模型
        Glib::RefPtr<Gtk::TreeModel> model = m_process_table.get_selection()->get_tree_view()->get_model();
        if (model) {
            // 使用之前保存的路径重新选择
            for (const auto& path : selected_paths) {
                Gtk::TreeModel::iterator iter = model->get_iter(path);
                if (iter) {
                    m_process_table.get_selection()->select(iter);
                }
            }
        }
    }
    
    return true;
}

bool MainWindow::on_system_timer_callback() {
    on_system_info_update();
    return true; // 继续定时器
}

bool MainWindow::on_system_info_update() {
    // 更新系统信息
    SystemInfo info = m_system_monitor.get_system_info();
    
    // 添加到历史记录
    m_cpu_history.push_back(info.cpu_percent);
    if (m_cpu_history.size() > 60) m_cpu_history.pop_front(); // 保留最近60个数据点
    
    m_memory_history.push_back(info.memory_percent);
    if (m_memory_history.size() > 60) m_memory_history.pop_front();
    
    // 使用磁盘读写速度而不是使用量百分比
    double disk_speed = (info.disk_read_speed_mbs + info.disk_write_speed_mbs) / 2.0;
    m_disk_history.push_back(disk_speed);
    if (m_disk_history.size() > 60) m_disk_history.pop_front();
    
    // 更新概览页面的按钮标签（修复：不再重复添加 %）
    Glib::ustring cpu_text = Glib::ustring::compose("CPU\n%1%%", 
        Glib::ustring::format(std::fixed, std::setprecision(1), info.cpu_percent));
    m_cpu_button.set_label(cpu_text);
    
    Glib::ustring memory_text = Glib::ustring::compose("内存\n%1%%", 
        Glib::ustring::format(std::fixed, std::setprecision(1), info.memory_percent));
    m_memory_button.set_label(memory_text);
    
    // 修改磁盘按钮显示为速度而非百分比
    double disk_avg_speed = (info.disk_read_speed_mbs + info.disk_write_speed_mbs) / 2.0;
    Glib::ustring disk_text = Glib::ustring::compose("磁盘\n%1 MB/s", 
        Glib::ustring::format(std::fixed, std::setprecision(1), disk_avg_speed));
    m_disk_button.set_label(disk_text);
    
    // 添加网络按钮显示速度
    double network_total_speed = (info.network_rx_bytes + info.network_tx_bytes) / (1024.0 * 1024.0); // 转换为MB/s
    Glib::ustring network_unit = "MB/s";
    
    // 根据速度大小选择合适的单位
    if (network_total_speed < 1.0) {
        network_total_speed = (info.network_rx_bytes + info.network_tx_bytes) / 1024.0; // 转换为KB/s
        network_unit = "KB/s";
        
        // 如果速度非常小，显示为B/s
        if (network_total_speed < 1.0) {
            network_total_speed = info.network_rx_bytes + info.network_tx_bytes;
            network_unit = "B/s";
        }
    }
    
    Glib::ustring network_text = Glib::ustring::compose("网络\n%1 %2", 
        Glib::ustring::format(std::fixed, std::setprecision(1), network_total_speed), 
        network_unit);
    m_network_button.set_label(network_text);
    
    // 更新系统详细信息
    // 解析并显示操作系统和发行版信息
    m_os_label_value.set_text(info.os_name);
    m_kernel_label_value.set_text(info.kernel_version);
    m_hostname_label_value.set_text(info.hostname);
    
    // 由于操作系统和发行版信息已合并，隐藏发行版标签
    m_distro_label_title.hide();
    m_distro_label_value.hide();
    
    Glib::ustring uptime_text = Glib::ustring::compose("%1小时 %2分钟 %3秒", 
        info.uptime_hours, info.uptime_minutes, info.uptime_seconds);
    m_uptime_label_value.set_text(uptime_text);
    
    Glib::ustring load_text = Glib::ustring::compose("%1%% %2, %3", 
        Glib::ustring::format(std::fixed, std::setprecision(2), info.load_average_1min),
        Glib::ustring::format(std::fixed, std::setprecision(2), info.load_average_5min),
        Glib::ustring::format(std::fixed, std::setprecision(2), info.load_average_15min));
    m_load_label_value.set_text(load_text);
    
    Glib::ustring processes_text = Glib::ustring::compose("总计: %1 运行中: %2 睡眠中: %3", 
        info.processes_total, info.processes_running, info.processes_sleeping);
    m_processes_label_value.set_text(processes_text);
    
    // 限制CPU型号显示长度
    std::string cpu_model = info.cpu_model;
    if (cpu_model.length() > 50) {
        cpu_model = cpu_model.substr(0, 47) + "...";
    }
    m_cpu_model_label_value.set_text(cpu_model);
    m_cpu_cores_label_value.set_text(std::to_string(info.cpu_cores));
    
    // 格式化网络使用情况显示
    Glib::ustring network_detail_text;
    if (info.network_rx_bytes > 1024*1024) {
        // MB
        network_detail_text = Glib::ustring::compose("接收: %1 MB 发送: %2 MB", 
            Glib::ustring::format(std::fixed, std::setprecision(1), info.network_rx_bytes / (1024.0*1024.0)),
            Glib::ustring::format(std::fixed, std::setprecision(1), info.network_tx_bytes / (1024.0*1024.0)));
    } else if (info.network_rx_bytes > 1024) {
        // KB
        network_detail_text = Glib::ustring::compose("接收: %1 KB 发送: %2 KB", 
            Glib::ustring::format(std::fixed, std::setprecision(1), info.network_rx_bytes / 1024.0),
            Glib::ustring::format(std::fixed, std::setprecision(1), info.network_tx_bytes / 1024.0));
    } else {
        // bytes
        network_detail_text = Glib::ustring::compose("接收: %1 bytes 发送: %2 bytes", 
            info.network_rx_bytes, info.network_tx_bytes);
    }
    m_network_label_value.set_text(network_detail_text);
    
    // 更新磁盘信息标签
    Glib::ustring disk_info_text = Glib::ustring::compose("磁盘使用量: %1 GB / %2 GB\n读取速度: %3 MB/s 写入速度: %4 MB/s",
        Glib::ustring::format(std::fixed, std::setprecision(1), info.disk_used_gb),
        Glib::ustring::format(std::fixed, std::setprecision(1), info.disk_total_gb),
        Glib::ustring::format(std::fixed, std::setprecision(1), info.disk_read_speed_mbs),
        Glib::ustring::format(std::fixed, std::setprecision(1), info.disk_write_speed_mbs));
    m_disk_info_label.set_text(disk_info_text);
    
    // 重绘图表
    m_cpu_drawing_area.queue_draw();
    m_memory_drawing_area.queue_draw();
    m_disk_drawing_area.queue_draw();
    
    return true;
}

void MainWindow::on_cpu_button_clicked() {
    // 不再切换到单独的标签页，而是在当前性能页面显示详情
    // 移除概览内容
    m_perf_summary_box.hide();
    
    // 显示CPU详情内容
    m_cpu_detail_box.show();
    
    // 添加返回按钮功能
    m_cpu_back_button.signal_clicked().connect([this]() {
        m_cpu_detail_box.hide();
        m_perf_summary_box.show();
    });
}

void MainWindow::on_memory_button_clicked() {
    // 不再切换到单独的标签页，而是在当前性能页面显示详情
    // 移除概览内容
    m_perf_summary_box.hide();
    
    // 显示内存详情内容
    m_memory_detail_box.show();
    
    // 添加返回按钮功能
    m_memory_back_button.signal_clicked().connect([this]() {
        m_memory_detail_box.hide();
        m_perf_summary_box.show();
    });
}

void MainWindow::on_disk_button_clicked() {
    // 不再切换到单独的标签页，而是在当前性能页面显示详情
    // 移除概览内容
    m_perf_summary_box.hide();
    
    // 显示磁盘详情内容
    m_disk_detail_box.show();
    
    // 添加返回按钮功能
    m_disk_back_button.signal_clicked().connect([this]() {
        m_disk_detail_box.hide();
        m_perf_summary_box.show();
    });
}

void MainWindow::on_network_button_clicked() {
    // 不再切换到单独的标签页，而是在当前性能页面显示详情
    // 移除概览内容
    m_perf_summary_box.hide();
    
    // 显示网络详情内容（暂时使用系统信息框作为占位符）
    m_system_info_box.show();
    
    // 添加返回按钮功能
    // 由于没有专门的网络详情页面，这里简单地提供返回功能
    // 实际实现中可能需要创建专门的网络详情页面
}

bool MainWindow::on_cpu_draw(const Cairo::RefPtr<Cairo::Context>& cr) {
    // 获取绘图区域尺寸
    Gtk::Allocation allocation = m_cpu_drawing_area.get_allocation();
    int width = allocation.get_width();
    int height = allocation.get_height();
    
    // 绘制背景
    cr->set_source_rgb(0.0, 0.0, 0.0); // 黑色背景
    cr->rectangle(0, 0, width, height);
    cr->fill();
    
    if (!m_cpu_history.empty()) {
        // 绘制网格
        cr->set_source_rgb(0.3, 0.3, 0.3); // 深灰色网格
        cr->set_line_width(1.0);
        
        // 水平网格线
        for (int i = 1; i < 4; ++i) {
            double y = height * i / 4.0;
            cr->move_to(0, y);
            cr->line_to(width, y);
            cr->stroke();
        }
        
        // 垂直网格线
        for (int i = 1; i < 6; ++i) {
            double x = width * i / 6.0;
            cr->move_to(x, 0);
            cr->line_to(x, height);
            cr->stroke();
        }
        
        // 绘制CPU使用率曲线
        cr->set_source_rgb(0.0, 1.0, 0.0); // 绿色曲线
        cr->set_line_width(2.0);
        
        double x_step = (double)width / std::max((int)m_cpu_history.size() - 1, 1);
        bool first_point = true;
        
        int i = 0;
        for (double value : m_cpu_history) {
            // 确保值在0-100范围内
            value = std::max(0.0, std::min(100.0, value));
            double x = i * x_step;
            double y = height - (value / 100.0) * height;
            
            if (first_point) {
                cr->move_to(x, y);
                first_point = false;
            } else {
                cr->line_to(x, y);
            }
            ++i;
        }
        cr->stroke();
        
        // 显示当前值
        if (!m_cpu_history.empty()) {
            double current_value = m_cpu_history.back();
            cr->set_source_rgb(1.0, 1.0, 1.0); // 白色文字
            cr->select_font_face("Sans", Cairo::FONT_SLANT_NORMAL, Cairo::FONT_WEIGHT_NORMAL);
            cr->set_font_size(12);
            
            Glib::ustring text = Glib::ustring::compose("CPU: %1%%", 
                Glib::ustring::format(std::fixed, std::setprecision(1), current_value));
            
            Cairo::TextExtents extents;
            cr->get_text_extents(text, extents);
            cr->move_to(width - extents.width - 10, extents.height + 10);
            cr->show_text(text);
        }
    }
    
    return true;
}

bool MainWindow::on_memory_draw(const Cairo::RefPtr<Cairo::Context>& cr) {
    // 获取绘图区域尺寸
    Gtk::Allocation allocation = m_memory_drawing_area.get_allocation();
    int width = allocation.get_width();
    int height = allocation.get_height();
    
    // 绘制背景
    cr->set_source_rgb(0.0, 0.0, 0.0); // 黑色背景
    cr->rectangle(0, 0, width, height);
    cr->fill();
    
    if (!m_memory_history.empty()) {
        // 绘制网格
        cr->set_source_rgb(0.3, 0.3, 0.3); // 深灰色网格
        cr->set_line_width(1.0);
        
        // 水平网格线
        for (int i = 1; i < 4; ++i) {
            double y = height * i / 4.0;
            cr->move_to(0, y);
            cr->line_to(width, y);
            cr->stroke();
        }
        
        // 垂直网格线
        for (int i = 1; i < 6; ++i) {
            double x = width * i / 6.0;
            cr->move_to(x, 0);
            cr->line_to(x, height);
            cr->stroke();
        }
        
        // 绘制内存使用率曲线
        cr->set_source_rgb(1.0, 1.0, 0.0); // 黄色曲线
        cr->set_line_width(2.0);
        
        double x_step = (double)width / std::max((int)m_memory_history.size() - 1, 1);
        bool first_point = true;
        
        int i = 0;
        for (double value : m_memory_history) {
            // 确保值在0-100范围内
            value = std::max(0.0, std::min(100.0, value));
            double x = i * x_step;
            double y = height - (value / 100.0) * height;
            
            if (first_point) {
                cr->move_to(x, y);
                first_point = false;
            } else {
                cr->line_to(x, y);
            }
            ++i;
        }
        cr->stroke();
        
        // 显示当前值
        if (!m_memory_history.empty()) {
            double current_value = m_memory_history.back();
            cr->set_source_rgb(1.0, 1.0, 1.0); // 白色文字
            cr->select_font_face("Sans", Cairo::FONT_SLANT_NORMAL, Cairo::FONT_WEIGHT_NORMAL);
            cr->set_font_size(12);
            
            Glib::ustring text = Glib::ustring::format(
                "内存: ", std::fixed, std::setprecision(1), current_value, "%");
            
            Cairo::TextExtents extents;
            cr->get_text_extents(text, extents);
            cr->move_to(width - extents.width - 10, extents.height + 10);
            cr->show_text(text);
        }
    }
    
    return true;
}

bool MainWindow::on_disk_draw(const Cairo::RefPtr<Cairo::Context>& cr) {
    // 获取绘图区域尺寸
    Gtk::Allocation allocation = m_disk_drawing_area.get_allocation();
    int width = allocation.get_width();
    int height = allocation.get_height();
    
    // 绘制背景
    cr->set_source_rgb(0.0, 0.0, 0.0); // 黑色背景
    cr->rectangle(0, 0, width, height);
    cr->fill();
    
    // 绘制网格
    cr->set_source_rgb(0.3, 0.3, 0.3); // 深灰色网格
    cr->set_line_width(1.0);
    
    // 水平网格线
    for (int i = 1; i < 4; ++i) {
        double y = height * i / 4.0;
        cr->move_to(0, y);
        cr->line_to(width, y);
        cr->stroke();
    }
    
    // 垂直网格线
    for (int i = 1; i < 6; ++i) {
        double x = width * i / 6.0;
        cr->move_to(x, 0);
        cr->line_to(x, height);
        cr->stroke();
    }
    
    // 绘制磁盘读写速度曲线（使用不同的颜色区分读写）
    if (!m_disk_history.empty()) {
        // 绘制读取速度曲线 - 蓝色
        cr->set_source_rgb(0.0, 0.5, 1.0);
        cr->set_line_width(2.0);
        
        double x_step = (double)width / std::max((int)m_disk_history.size() - 1, 1);
        bool first_point = true;
        
        int i = 0;
        for (double value : m_disk_history) {
            // 确保值在0-100范围内
            value = std::max(0.0, std::min(100.0, value));
            double x = i * x_step;
            double y = height - (value / 100.0) * height;
            
            if (first_point) {
                cr->move_to(x, y);
                first_point = false;
            } else {
                cr->line_to(x, y);
            }
            ++i;
        }
        cr->stroke();
    }
    
    // 显示当前读写速度信息
    cr->set_source_rgb(1.0, 1.0, 1.0); // 白色文字
    cr->select_font_face("Sans", Cairo::FONT_SLANT_NORMAL, Cairo::FONT_WEIGHT_NORMAL);
    cr->set_font_size(12);
    
    // 显示磁盘使用量信息（从系统监控器获取）
    SystemInfo info = m_system_monitor.get_system_info();
    Glib::ustring usage_text = Glib::ustring::compose("使用量: %1 GB / %2 GB", 
        Glib::ustring::format(std::fixed, std::setprecision(1), info.disk_used_gb),
        Glib::ustring::format(std::fixed, std::setprecision(1), info.disk_total_gb));
    
    Cairo::TextExtents usage_extents;
    cr->get_text_extents(usage_text, usage_extents);
    cr->move_to(10, usage_extents.height + 10);
    cr->show_text(usage_text);
    
    // 显示读写速度
    if (!m_disk_history.empty()) {
        double current_value = m_disk_history.back();
        Glib::ustring speed_text = Glib::ustring::compose("读写速度: %1 MB/s", 
            Glib::ustring::format(std::fixed, std::setprecision(1), current_value));
        
        Cairo::TextExtents speed_extents;
        cr->get_text_extents(speed_text, speed_extents);
        cr->move_to(10, usage_extents.height + speed_extents.height + 20);
        cr->show_text(speed_text);
    }
    
    return true;
}
